//负责视图变量的替换
//打上标识补丁
//变成一个有标识的节点结构
import {
  randomNum
} from "../shared/utils";

const
  //匹配内容：<h1>{{count}}</h1>
  //规则：<>+ 一次或多次非贪婪 + {{}} +</>
  //拿{{}}里面的变量(key) 和 整个元素内容(node)
  reg_html = /\<.+?\>\{\{(.+?)\}\}\<\/.+?\>/g,
  //拿标签名 h1
  reg_tag = /\<(.+?)\>/,
  //匹配内容：{{}}里的变量
  reg_var = /\{\{(.+?)\}\}/g;

//记录每一次statePool存值的初始化数字
let o = 0;

/**
 * 希望的statePool结构：
 * statePool = [
 *   {
 *     mark: _mark,
 *     state: value
 *   }
 * ]
 */
export const statePool = [];

export function stateFormat(template, state) {
  // console.log(template);
  /**
   * <h1>{{count}}</h1>
   * <h2>{{name}}</h2>
   * <button data-mark="1628088949812">+</button>
   * <button data-mark="1628088950886">-</button>
   * <button data-mark="1628088943621">Change Name</button>
   */
  // console.log(state);
  //Proxy {count: 0, name: "datian"}

  let _state = {};

  template = template.replace(reg_html, function (node, key) {
    // console.log(node); <h1>{{count}}</h1>
    // console.log(key); count

    const
      matched = node.match(reg_tag),
      // console.log(matched);
      //["<h1>", "h1", index: 0, input: "<h1>{{count}}</h1>", groups: undefined]
      _mark = randomNum();

    _state.mark = _mark;
    statePool.push(_state);
    // console.log(statePool);
    //[{mark: 1628090295148}, {mark: 1628090292471}]

    //清空_state
    _state = {};

    //将替换好的<h1 data-mark="">undefined</h1>显示在页面
    //打上标识好的补丁
    return `<${matched[1]} data-mark="${_mark}">{{${key}}}</${matched[1]}>`
  });

  //替换标签里的文本内容
  template = template.replace(reg_var, function (node, key) {
    // console.log(node); {{count}}
    // console.log(key); count
    let _var = key.trim();

    //写法state.a / state.a.b 用split()区分
    const _varArr = _var.split('.');
    //console.log(_varArr); 
    //["count"] ["name"]

    let i = 0;
    while (i < _varArr.length) {
      //重新赋值
      //用法：访问state.下面的下面的下面等
      _var = state[_varArr[i]];
      i++;
    }

    //记录每一次的存值 o下标不重复
    statePool[o].state = _varArr;
    o++;
    //console.log(statePool);
    /**
     * [
     *   {mark: 1628091740739, state: ["count"]}, 
     *   {mark: 1628091737697, state: ["name"]}
     * ]
     */

    //该_var值重新替换{{}}里的内容
    return _var;
  })

  return template;
}